package org.jks.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.config.Config;
import org.jks.model.ApplyOrder;
import org.jks.model.Department;
import org.jks.model.Device;
import org.jks.model.DeviceApply;
import org.jks.model.Flight;
import org.jks.report.model.ReportDeviceApplyModel;
import org.jks.request.model.Ids;
import org.jks.request.model.UIApplyOrder;
import org.jks.request.model.UIDeviceApply;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UITable;
import org.jks.service.DeviceApplyService;
import org.jks.util.DateUtil;
import org.jks.util.ExportUtil;
import org.jks.util.JsonUtil;
import org.jks.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

@Controller
@RequestMapping("/device_apply")
public class DeviceApplyController extends MultiActionController {
	@Autowired
	DeviceApplyService deviceApplyService;

	@RequestMapping(value = "/add")
	public void add(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		ActionResult ar = new ActionResult();
		String json = "";
		String OrderNo = "DA_" + DateUtil.toString(new Date(), "yyyyMMddHHmmss");
		try {
			json = JsonUtil.getJson(request.getReader());
			UIDeviceApply uiDeviceApply = (UIDeviceApply) JsonUtil.Json2Object(json, UIDeviceApply.class);
			DeviceApply deviceApply = new DeviceApply();
			Department department = new Department();
			department.setId(uiDeviceApply.getDepartmentId());
			deviceApply.setDepartment(department);
			Flight group = new Flight();
			group.setId(uiDeviceApply.getGroupId()); 
			deviceApply.setGroup(group);
			deviceApply.setTime(DateUtil.toDate(uiDeviceApply.getTime(), "yyyy-MM-dd HH:mm:ss"));
			deviceApply.setDesp(uiDeviceApply.getDesp());
			deviceApply.setOrderNo(OrderNo);
			
			List<ApplyOrder> applyOrders = new ArrayList<ApplyOrder>();
			for(UIApplyOrder uiApplyOrder : uiDeviceApply.getOrders()){
				ApplyOrder applyOrder = new ApplyOrder();
				Device device = new Device();
				device.setId(uiApplyOrder.getDeviceId());
				applyOrder.setDevice(device);
				applyOrder.setCount(uiApplyOrder.getCount());
				applyOrder.setUnitPrice(uiApplyOrder.getUnitPrice());
				applyOrder.setDeviceApply(deviceApply);
				applyOrders.add(applyOrder);
			}
			deviceApply.setApplyOrders(applyOrders);
			deviceApplyService.save(deviceApply);
			ar.setSuccess(true);
		} catch (IOException e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	public void add(DeviceApply deviceApply, HttpServletRequest request,
			HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		try {
			deviceApplyService.save(deviceApply);
			ar.setSuccess(true);
			ar.setData(deviceApply);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable long id, HttpServletRequest request,
			HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		try {
			deviceApplyService.delete(id);
			ar.setSuccess(true);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/delete")
	public void delete(Ids ids, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ActionResult ar = new ActionResult();
		try{
			for(long id: ids.getIds()){
				DeviceApply deviceApply = deviceApplyService.findById(id);
				if(deviceApply != null){
					deviceApplyService.delete(deviceApply);
				}
			}
			ar.setSuccess(true);
		}
		catch(Exception e){
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/detail/{id}")
	public ModelAndView detail(@PathVariable long id, HttpServletRequest request, HttpSession session, HttpServletResponse response, Map<String,Object> model){
		try {
			DeviceApply deviceApply = deviceApplyService.findById(id);
			if(deviceApply!=null){
				deviceApply.getApplyOrders().size();
				for(ApplyOrder applyOrder : deviceApply.getApplyOrders()){
					applyOrder.setDeviceApply(null);
				}
			}
			model.put("deviceApply", JsonUtil.Object2Json(deviceApply));
		} catch (Exception e) {
			e.printStackTrace();
		}
		Config.init(request, response, session, model);
		return new ModelAndView("wuziMgr/wz_apply_detail", model);
	}

	@RequestMapping("/update")
	public void update(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) {
		ActionResult ar = new ActionResult();
		String json = "";
		try {
			json = JsonUtil.getJson(request.getReader());
			UIDeviceApply uiDeviceApply = (UIDeviceApply) JsonUtil.Json2Object(json, UIDeviceApply.class);
			DeviceApply deviceApply = deviceApplyService.findById(uiDeviceApply.getId());
			Department department = new Department();
			department.setId(uiDeviceApply.getDepartmentId());
			deviceApply.setDepartment(department);
			Flight group = new Flight();
			group.setId(uiDeviceApply.getGroupId()); 
			deviceApply.setGroup(group);
			deviceApply.setTime(DateUtil.toDate(uiDeviceApply.getTime(), "yyyy-MM-dd HH:mm:ss"));
			deviceApply.setDesp(uiDeviceApply.getDesp());
			deviceApply.getApplyOrders().clear();
			deviceApplyService.update(deviceApply);
			
			List<ApplyOrder> applyOrders = new ArrayList<ApplyOrder>();
			for(UIApplyOrder uiApplyOrder : uiDeviceApply.getOrders()){
				ApplyOrder applyOrder = new ApplyOrder();
				Device device = new Device();
				device.setId(uiApplyOrder.getDeviceId());
				applyOrder.setDevice(device);
				applyOrder.setCount(uiApplyOrder.getCount());
				applyOrder.setUnitPrice(uiApplyOrder.getUnitPrice());
				applyOrder.setDeviceApply(deviceApply);
				applyOrders.add(applyOrder);
			}
			deviceApply.setApplyOrders(applyOrders);
			deviceApplyService.update(deviceApply);
			ar.setSuccess(true);
		} catch (IOException e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	public void update(DeviceApply deviceApply, HttpServletRequest request,
			HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		try {
			deviceApplyService.update(deviceApply);
			ar.setSuccess(true);
			ar.setData(deviceApply);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}

	@RequestMapping("/all")
	public void all(HttpServletRequest request, HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		String[] limit = request.getParameterValues("limit");
		String[] pages = request.getParameterValues("page");
		int pagesize = 25;
		int page = 1;
		if(limit.length > 0){
			pagesize = Integer.valueOf(limit[0]);
		}
		if(pages.length > 0){
			page = Integer.valueOf(pages[0]);
		}
		try {
			long total = deviceApplyService.count();
			List<DeviceApply> deviceApplies = deviceApplyService.list(page, pagesize);
			for(DeviceApply deviceApply : deviceApplies){
				deviceApply.setApplyOrders(null);
			}
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setTotal(total);
			table.setRows(deviceApplies);
			ar.setData(table);
		} catch (Exception e) {
			ar.setMsg(e.getMessage());
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/export/{id}")
	public void export(@PathVariable long id, HttpServletRequest request, HttpServletResponse response){
		DeviceApply deviceApply = null;
		try {
			deviceApply = deviceApplyService.findById(id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(deviceApply != null){
			String basePath = request.getServletContext().getRealPath("/");
			String templatePath = basePath + File.separator + "templates" + File.separator + "report" + File.separator + "word";
			ReportDeviceApplyModel rdam = deviceApply.toReportModel();
			ExportUtil.export(response, templatePath, "wz_apply.vm", "物资申请", "doc", rdam);
		}
	}
}
